package net.wanho.shop.service.impl;

import lombok.RequiredArgsConstructor;
import net.wanho.shop.common.CaptchaConstant;
import net.wanho.shop.common.UserConstant;
import net.wanho.shop.dto.SMSLoginDTO;
import net.wanho.shop.exception.LoginErrorException;
import net.wanho.shop.mapper.RoleMapper;
import net.wanho.shop.mapper.UserMapper;
import net.wanho.shop.po.Role;
import net.wanho.shop.po.User;
import net.wanho.shop.service.SmsService;
import net.wanho.shop.util.JwtUtil;
import net.wanho.shop.util.SMSUtil;
import net.wanho.shop.vo.LoginUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 这个类是：
 *
 * @author: MENG HU WANG
 * @date: 2025/1/4 23:13
 * @version: 1.0
 */

@Service
@RequiredArgsConstructor
public class SmsServiceImpl implements SmsService {

    private final StringRedisTemplate redisTemplate;
    private final StringRedisTemplate stringRedisTemplate;
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;


    @Override
    public void sendSmsCode(String phone) {
        SMSUtil smsUtil = new SMSUtil();
        // 生成验证码
        int code = (int) Math.ceil(Math.random() * 900000 + 100000);

//        String redisCode = String.valueOf(code);
//        String smsCode = String.valueOf(code);
//        System.out.println(redisCode + "      " + smsCode);
        smsUtil.sendMessage(phone, String.valueOf(code));
        // 将验证码保存到redis中
        redisTemplate.opsForValue().set(CaptchaConstant.SMS_CAPTCHA_PREFIX, String.valueOf(code), CaptchaConstant.CAPTCHA_EXPIRE, TimeUnit.MINUTES);
    }

    @Override
    public LoginUserVo smsLogin(SMSLoginDTO smsLoginDTO) {
        User user = userMapper.selectByMobile(smsLoginDTO.getPhone());
        String smsCode = stringRedisTemplate.opsForValue().get(CaptchaConstant.SMS_CAPTCHA_PREFIX);
        if (user == null)
            throw new RuntimeException("用户不存在");
        if (Objects.equals(user.getMgState(), UserConstant.STATE_DISABLE))
            throw new LoginErrorException("用户以禁用");
        if (!Objects.equals(smsCode, smsLoginDTO.getSmsCode()))
            throw new LoginErrorException("验证码错误");

        // 5.生成token
        Map<String, Object> payload = new HashMap<>();
        payload.put(UserConstant.USER_ID, user.getId());
        payload.put(UserConstant.USER_NAME, user.getUsername());
        String token = JwtUtil.generate(payload);

        LoginUserVo loginUserVo = new LoginUserVo();
        // 6.拷贝属性
        BeanUtils.copyProperties(user, loginUserVo);
        // 7.设置token
        loginUserVo.setToken("Bearer " + token);
        // 8.查询角色名称
        Role role = roleMapper.selectById(user.getRoleId());
        loginUserVo.setRoleName(role.getRoleName());

        return loginUserVo;
    }
}
